import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class Race{
	
	private HashMap<Integer,Athlete> athletes;
	
	public static final int NOT_STARTED = -1;
	
	public static final int CHECKPOINTS = 4;
	
	public static final int ERROR_PREVIOUS_CHECKPOINT = -1;
	public static final int ERROR_SKIPPED_CHECKPOINT = -2;
	public static final int ERROR_SAME_CHECKPOINT = -3;
	public static final int ERROR_INVALID_CHECKPOINT = -4;
	public static final int ERROR_INVALID_DORSAL = -5;
	
	public Race (){
		athletes = new HashMap <Integer,Athlete> ();
	}
	
	public long checkPoint (int dorsal, int checkPoint, Date time){
		if (!athletes.containsKey(dorsal))
			return ERROR_INVALID_DORSAL;
		long retValue = athletes.get(dorsal).checkPoint(checkPoint, time);
		return retValue;
	}
	
	public List<Athlete> getClassification (){
		ArrayList <Athlete> list = new ArrayList<Athlete>(athletes.values());
		Collections.sort(list,new AthleteComparator());
		
		return list;
	}
	
	public void loadAthletes (String excelFile) throws InvalidFormatException, IOException{
		InputStream is = new FileInputStream(excelFile);
		
		Workbook w = WorkbookFactory.create(is);
		Sheet sheet = w.getSheetAt(0);
		
		int rows = sheet.getPhysicalNumberOfRows();
		
		for (int i=1; i<rows; i++){
			Row r = sheet.getRow(i);
			int number = (int) r.getCell(0).getNumericCellValue();
			String name = r.getCell(1).getStringCellValue();
			r.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
			String phone = r.getCell(2).getStringCellValue();
			
			athletes.put(number, new Athlete(number,name,phone));
		}
		
		is.close();
	}
	
	public boolean isOver (){
		return false;
	}
	
}
